import os
import re
import shutil
from openpyxl import Workbook
from datetime import datetime
from flask import Flask, render_template_string
import openpyxl
from threading import Thread

app = Flask(__name__)

# 定义文件名匹配模式
pattern1 = re.compile(r'(.+)-(.+)-(.+)-软通动力\.pdf$', re.I)
pattern2 = re.compile(r'(.+)-(.+)-(.+)\.pdf$', re.I)

# 第一步：处理PDF文件分类
def resumeList():
    pdf_count = 0
    for filename in os.listdir('.'):
        if filename.lower().endswith('.pdf'):
            match = pattern1.match(filename) or pattern2.match(filename)
            if match:
                name, position, city = match.groups()
                # 创建城市目录
                city_dir = os.path.join(os.getcwd(), city)
                os.makedirs(city_dir, exist_ok=True)
                
                # 移动文件（覆盖已存在文件）
                src = os.path.join(os.getcwd(), filename)
                dst = os.path.join(city_dir, filename)
                shutil.move(src, dst)
                pdf_count += 1
    return pdf_count

# 第二步：生成Excel文件
def generate_excels():
    for root, dirs, files in os.walk('.'):
        # 跳过根目录
        if root == '.':
            continue
            
        # 仅处理城市目录
        excel_path = os.path.join(root, 'list.xlsx')
        wb = Workbook()
        ws = wb.active
        
        # 设置表头
        headers = ['序号', '日期', '文件全名', '姓名', '岗位', '城市', '评定']
        ws.append(headers)
        
        # 遍历PDF文件
        for idx, filename in enumerate(files):
            if filename.lower().endswith('.pdf'):
                match = pattern1.match(filename) or pattern2.match(filename)
                if match:
                    name, position, city = match.groups()
                    # 添加数据行
                    row = [
                        idx+1,
                        datetime.now().strftime('%Y-%m-%d'),
                        filename,
                        name,
                        position,
                        city,
                        ''  # 留空评定列
                    ]
                    ws.append(row)
        
        # 自动调整列宽
        for column in ws.columns:
            max_length = 0
            column_letter = column[0].column_letter
            for cell in column:
                try:
                    value_len = len(str(cell.value)) * 2  # 中文字符按双倍计算
                    if value_len > max_length:
                        max_length = value_len
                except:
                    pass
            adjusted_width = (max_length + 2)
            ws.column_dimensions[column_letter].width = adjusted_width
        
        # 保存Excel文件
        wb.save(excel_path)

# Web服务器路由
@app.route('/')
def show_tables():
    html = '<h1>简历列表</h1>'
    for city in os.listdir('.'):
        if os.path.isdir(city):
            excel_path = os.path.join(city, 'list.xlsx')
            if os.path.exists(excel_path):
                html += f'<h2>{city}</h2>'
                wb = openpyxl.load_workbook(excel_path)
                ws = wb.active
                html += '<table border="1"><tr>'
                for cell in ws[1]:
                    html += f'<th>{cell.value}</th>'
                html += '</tr>'
                for row in ws.iter_rows(min_row=2):
                    html += '<tr>'
                    for cell in row:
                        html += f'<td>{cell.value}</td>'
                    html += '</tr>'
                html += '</table>'
    return html

if __name__ == '__main__':
    count = resumeList()
    if count > 0:
        generate_excels()
    # 在后台启动Flask服务
    Thread(target=lambda: app.run(port=9899, debug=False)).start()
    print("文件整理完成，Web服务已启动：http://localhost:9899")
    print("按Ctrl+C停止服务")
    try:
        while True:
            pass
    except KeyboardInterrupt:
        os._exit(0)
    print("文件整理完成")